package sshx

import (
	"fmt"
	"time"
)

// SSHConfig 表示SSH配置的结构体
type SSHConfig struct {
	Host     string
	Port     int
	User     string
	Password string
	KeyPath  string
	Timeout  time.Duration
}

// SSHConfigOption 定义SSH配置的选项
type SSHConfigOption func(*SSHConfig)

// WithPort 设置端口
func WithPort(port int) SSHConfigOption {
	return func(c *SSHConfig) {
		c.Port = port
	}
}

// WithUser 设置用户名
func WithUser(user string) SSHConfigOption {
	return func(c *SSHConfig) {
		c.User = user
	}
}

// WithPassword 设置密码
func WithPassword(password string) SSHConfigOption {
	return func(c *SSHConfig) {
		c.Password = password
	}
}

// WithKeyPath 设置密钥路径
func WithKeyPath(keyPath string) SSHConfigOption {
	return func(c *SSHConfig) {
		c.KeyPath = keyPath
	}
}

// WithTimeout 设置超时时间
func WithTimeout(timeout time.Duration) SSHConfigOption {
	return func(c *SSHConfig) {
		c.Timeout = timeout
	}
}

// NewSSHConfig 创建一个新的SSH配置实例
func NewSSHConfig(host string, opts ...SSHConfigOption) *SSHConfig {
	config := &SSHConfig{
		Host:    host,
		Port:    22,
		User:    "root", // 默认用户
		Timeout: 30 * time.Second,
	}

	for _, opt := range opts {
		opt(config)
	}

	return config
}

// ValidateSSHConfig validates server configuration parameters and sets default values
func ValidateSSHConfig(config *SSHConfig) error {
	if config.Host == "" {
		return fmt.Errorf("host address cannot be empty")
	}

	if config.Port <= 0 {
		config.Port = 22 // Set default SSH port
	}

	if config.User == "" {
		config.User = "root" // Set default username
	}

	if config.Password == "" && config.KeyPath == "" {
		return fmt.Errorf("must provide password or key file path")
	}

	return nil
}
